package cn.edu.cug.cs.gtl.gsm.jdbc.oracle;

import cn.edu.cug.cs.gtl.common.Identifier;
import cn.edu.cug.cs.gtl.gsm.item.ByteArray;
import cn.edu.cug.cs.gtl.gsm.item.DataItem;
import cn.edu.cug.cs.gtl.gsm.item.MetaItem;
import cn.edu.cug.cs.gtl.util.StringUtils;

import java.io.IOException;
import java.sql.*;

public class DataTables {
    private String DATA_TABLE_NAME;
    private String SQL_DROP_DATA_TABLE;
    private String SQL_CREATE_DATA_TABLE;
    private String SQL_DELETE_DATA_TABLE_DATA;
    private String SQL_SELECT_DATA_TABLE_DATA;
    private String SQL_DELETE_ALL_DATA_TABLE_DATA;
    private String SQL_INSERT_DATA_TABLE_DATA;
    private String SQL_UPDATE_DATA_TABLE_DATA;
    private String SQL_SELECT_FOR_UPDATE_DATA_TABLE_DATA;


    protected Connection connection;
    MetaItem metaItem;


    public DataTables(Connection connection,MetaItem metaItem) {
        this.metaItem=metaItem;
        this.connection = connection;
        setCurrentTableOrder(0);
    }

    public void setCurrentTableOrder(int order){
        DATA_TABLE_NAME=metaItem.getBaseName()+".rdb_sm_data_"+metaItem.getBaseName()+"_"+String.valueOf(order);
        SQL_DROP_DATA_TABLE= "DROP TABLE "+DATA_TABLE_NAME;
        SQL_CREATE_DATA_TABLE= "CREATE TABLE " + DATA_TABLE_NAME + " ( page_identifier  VARCHAR2(255) PRIMARY KEY, page_content CLOB)";
        SQL_DELETE_DATA_TABLE_DATA= "DELETE FROM " + DATA_TABLE_NAME + " WHERE page_identifier = ?";
        SQL_SELECT_DATA_TABLE_DATA= "SELECT page_content FROM " + DATA_TABLE_NAME + " WHERE page_identifier = ?";
        SQL_DELETE_ALL_DATA_TABLE_DATA= "DELETE FROM " + DATA_TABLE_NAME ;
        SQL_INSERT_DATA_TABLE_DATA= "INSERT INTO " + DATA_TABLE_NAME + " VALUES (?,?)";
        SQL_UPDATE_DATA_TABLE_DATA= "UPDATE " + DATA_TABLE_NAME + " SET page_content = empty_clob() WHERE page_identifier=?";
        SQL_SELECT_FOR_UPDATE_DATA_TABLE_DATA= "SELECT page_content FROM " + DATA_TABLE_NAME + " WHERE page_identifier = ? FOR UPDATE";
    }

    public boolean create() throws SQLException {
        Statement statement = connection.createStatement();
        boolean r =  statement.execute(SQL_CREATE_DATA_TABLE);
        statement.close();
        return r;
    }

    public boolean drop() throws SQLException {
        if(exists()) {
            Statement statement = connection.createStatement();
            boolean r = statement.execute(SQL_DROP_DATA_TABLE);
            statement.close();
            return r;
        }
        else
            return true;
    }

    public boolean delete(Identifier pageIdentifier) throws SQLException{
        PreparedStatement statement = connection.prepareStatement(SQL_DELETE_DATA_TABLE_DATA);
        statement.setString(1,pageIdentifier.toString());
        boolean r =  statement.execute();
        statement.close();
        return r;
    }

    public boolean deleteAll() throws SQLException{
        Statement statement = connection.createStatement();
        boolean r =  statement.execute(SQL_DELETE_ALL_DATA_TABLE_DATA);
        statement.close();
        return r;
    }

    public boolean insert(DataItem pageContent) throws SQLException, IOException {
        PreparedStatement statement = connection.prepareStatement(SQL_INSERT_DATA_TABLE_DATA);

        statement.setString(1,pageContent.getPageIdentifier().toString());
        ByteArray byteArray = new ByteArray(pageContent.getPageContent());
        Clob b = connection.createClob();
        b.setString(1,byteArray.storeToCompressString());
        statement.setClob(2,b);
        boolean r =  statement.execute();
        statement.close();
        return r;
    }

    public boolean update(DataItem pageContent) throws SQLException, IOException {
        PreparedStatement statement = connection.prepareStatement(SQL_UPDATE_DATA_TABLE_DATA);
        statement.setString(1,pageContent.getPageIdentifier().toString());
        statement.executeUpdate();
        statement.close();
        statement = connection.prepareStatement(SQL_SELECT_FOR_UPDATE_DATA_TABLE_DATA);
        statement.setString(1,pageContent.getPageIdentifier().toString());
        ResultSet rs = statement.executeQuery();
        if(rs.next()) {
            Clob b = rs.getClob(1);
            ByteArray byteArray = new ByteArray(pageContent.getPageContent());
            b.setString(1,byteArray.storeToCompressString());
            statement.executeUpdate();
        }
        rs.close();
        statement.close();
        return true;
    }

    public DataItem select(Identifier pageIdentifier) throws SQLException, IOException {
        PreparedStatement statement = connection.prepareStatement(SQL_SELECT_DATA_TABLE_DATA);
        statement.setString(1,pageIdentifier.toString());
        ResultSet r =  statement.executeQuery();
        Clob compressZip = null;
        while(r.next()){
            compressZip = r.getClob(1);
            if(compressZip!=null) {
                ByteArray byteArray = new ByteArray();
                byteArray.loadFromCompressString(compressZip.getSubString(1,(int)compressZip.length()));
                DataItem dataItem = new DataItem((Identifier) pageIdentifier.clone(), byteArray.getBytes());
                r.close();
                statement.close();
                return dataItem;
            }
            else {
                r.close();
                statement.close();
                return null;
            }
        }
        r.close();
        statement.close();
        return null;
    }

    public boolean exists() throws SQLException{
        String []sa = StringUtils.split(DATA_TABLE_NAME,".");
        return OracleStorageManager.exists(connection,sa[0],sa[1]);
    }

}
